<template>
  <div class="dialog">
    <el-dialog width="70%" title="选择产品" :visible="true" :close-on-click-modal="false" :before-close="close">
      <pf-table
        ref="pfTable"
        v-model="form"
        class="product-table"
        :columns="columns"
        :form-items="formItems"
        @get-table-data="getTableData"
        @selection-change="handleSelectionChange"
      />
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getProductList } from '@/api/ticket'

export default {
  name: 'AddProduct',
  components: {},
  props: {
    productList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      form: {},
      selectionList: []
    }
  },
  computed: {
    ...mapGetters([
      'currentEnterprise',
      'currentSite'
    ]),
    formItems() {
      return [
        {
          type: 'input',
          label: '产品名称',
          prop: 'name',
          span: 8
        }, {
          type: 'select',
          label: '产品类目',
          prop: 'shopName',
          span: 8
        }
      ]
    },
    columns() {
      const attrs = { 'min-width': '150px' }
      return [
        { attrs: { type: 'selection', selectable: this.selectable }},
        { label: '产品名称', prop: 'productName', attrs },
        { label: '产品图片', prop: 'productImg', attrs },
        { label: '产品规格', prop: 'productPrice', attrs },
        { label: '规格单位', prop: 'shopName', attrs },
        { label: '价格', prop: 'shopName', attrs },
        { label: '所属店铺', prop: 'shopName', attrs }
      ]
    }
  },

  created() {
  },

  methods: {

    getTableData({ pageNo, pageSize, ...formQuery }, done) {
      this.loading = true
      const data = {
        pageNo,
        pageSize,
        ...formQuery
      }
      getProductList(data).then(res => {
        this.loading = false
        done({ data: res.data || [], total: res.count || 0 })
      }).catch(() => {
        done({ data: [], total: 0 })
        this.loading = false
      })
    },

    // 设置是否可选
    selectable(row) {
      const ids = this.productList.map(item => item.productId)
      if (ids.includes(row.productId)) {
        return false
      } else {
        return true
      }
    },

    // 选择
    handleSelectionChange(selection) {
      this.selectionList = selection
    },

    // 取消
    close() {
      this.$emit('close')
    },

    // 确认
    confirm() {
      if (this.selectionList.length) {
        this.selectionList.map(item => {
          item.productNum = 1
        })
        this.$emit('confirm', this.selectionList)
      } else {
        this.$message.error('请选择产品')
      }
    }
  }

}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body{
  padding: 10px 20px;
}
</style>
